<template>
  <div class="fillcontain">
    <head-top></head-top>
    <el-radio-group v-model="userType" class="type_change" @change="onTypeChange">
      <el-radio-button label="学生"></el-radio-button>
      <el-radio-button label="老师"></el-radio-button>
    </el-radio-group>
    <el-button type="text" @click="dialogFormVisible = true" class="add_user">新增用户</el-button>
    <el-dialog v-loading="loading" title="增加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth">
          <el-input v-model="form.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth">
          <el-select v-model="form.role" placeholder="选择身份">
            <el-option label="老师" value="2"></el-option>
            <el-option label="学生" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </div>
    </el-dialog>
    <div class="table_container">
      <el-table :data="tableData" border highlight-current-row style="width: 100%">
        <el-table-column fixed property="username" label="用户姓名" width="120">
        </el-table-column>
        <el-table-column property="id" label="用户id" width="120">
        </el-table-column>
        <el-table-column property="phone" label="手机号" width="180">
        </el-table-column>
        <el-table-column v-if="currentRole==0" property="admin_name" label="管理员" width="120">
        </el-table-column>
        <el-table-column property="created_at" label="注册日期" width="220">
        </el-table-column>
        <el-table-column property="updated_at" label="更新日期" width="220">
        </el-table-column>
        <el-table-column property="role" label="用户权限" width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template scope="scope">
                 <el-button type="text" @click="handleClick(scope.row)" size="small">修改</el-button>
                  <el-button type="text" @click="handleDeleteClick(scope.row)" size="small">删除</el-button>
                 <el-button  v-if="scope.row.status!=0" type="text" @click="confirmUser(scope.row)" size="small">确认</el-button>
</template>
    </el-table-column>
      </el-table>

      <el-dialog v-loading="changeLoading" :title="isChange?'修改用户信息':'确认用户信息'" :visible.sync="dialogChangeVisible">
      <el-form :model="changeForm">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="changeForm.username" :placeholder="changeForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" :label-width="formLabelWidth">
          <el-input v-model="changeForm.phone" :placeholder="changeForm.phone" auto-complete="off"></el-input>
        </el-form-item>
          <el-form-item v-if="currentRole==0" label="绑定管理员" :label-width="formLabelWidth">
         <el-autocomplete v-model="changeForm.admin_name" :fetch-suggestions="queryTeacherSearchAsync" placeholder="请输入管理员姓名或手机号" style="width: 100%;" @select="teacherSelect"></el-autocomplete>
            </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth">
           <el-input :placeholder="changeForm.role==2?'老师':'学生'" auto-complete="off" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChangeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeUser()">确 定</el-button>
      </div>
    </el-dialog>

      <div class="Pagination" style="text-align: left;margin-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="50" layout="total, prev, pager, next" :total="count">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import headTop from "../components/headTop";
import {
  getUserList,
  getUserCount,
  addUserInfo,
  updateUserInfo,
  deleteUser,
  searchUser
} from "@/api/getData";

export default {
  data() {
    return {
      loading: false,
      changeLoading: false,
      dialogFormVisible: false,
      dialogChangeVisible: false,
      formLabelWidth: "120px",
      currentRole: window.localStorage.getItem("current-user-role"),
      changeForm: {},
      userType: "学生",
      form: {
        username: "",
        role: "3",
        password: "",
        phone: ""
      },
      tableData: [],
      currentRow: null,
      limit: 20,
      count: 0,
      currentPage: 1,
      isChange: true
    };
  },
  components: {
    headTop
  },
  created() {
    this.initData();
    console.log(this.currentRole);
  },
  methods: {
    async queryTeacherSearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const res = await searchUser(1, {
            keyword: queryString
          });
          if (res.resCode == 0) {
            res.data.forEach(item => {
              item.value = item.username;
            });
            cb(res.data);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    teacherSelect(admin) {
      console.log(admin);
      this.changeForm.admin_id = admin.id;
      this.changeForm.admin_name = admin.username;
    },
    handleClick(row) {
      this.isChange = true;
      this.dialogChangeVisible = true;
      this.changeForm = row;
    },
    handleDeleteClick(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUserById(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async deleteUserById(id) {
      let reqData = {};
      reqData.id = id;
      const res = await deleteUser(reqData);
      if (res.resCode == 0) {
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.initData();
      } else {
        this.$message.error(res.resMsg);
      }
    },
    confirmUser(row) {
      this.isChange = false;
      this.dialogChangeVisible = true;
      this.changeForm = row;
      this.changeForm.admin_id = window.localStorage.getItem(
        "current-admin-id"
      );
    },
    onTypeChange(label) {
      this.getUsers();
    },
    async initData() {
      try {
        this.getUsers();
      } catch (err) {
        console.log("获取数据失败", err);
      }
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUsers();
    },
    async getUsers() {
      var user_type = this.userType == "学生" ? 3 : 2;
      const res = await getUserList(user_type, this.currentPage);
      this.count = res.data.count;
      if (res.resCode == 0) {
        this.tableData = [];
        res.data.data.forEach(item => {
          const tableData = {};
          tableData.id = item.id;
          tableData.admin_id = item.admin_id;
          tableData.admin_name = item.admin_name;
          tableData.username = item.username;
          tableData.avatar = item.avatar;
          tableData.created_at = item.created_at;
          tableData.updated_at = item.updated_at;
          tableData.role = item.role;
          tableData.status = item.status;
          tableData.openid = item.openid;
          tableData.phone = item.phone;
          this.tableData.push(tableData);
        });
      }
    },
    async updateUser() {
      if (!this.isChange) {
        this.changeForm.status = 0;
      }
      const res = await updateUserInfo(this.changeForm);
      if (res.resCode == 0) {
        this.$message({
          type: "success",
          message: this.isChange ? "修改成功!" : "确认成功"
        });
        this.dialogChangeVisible = false;
      } else {
        this.$message.error(res.resMsg);
      }
    },

    changeUser() {
      this.$confirm(
        this.isChange ? "是否确认修改用户信息?" : "是否确认用户信息?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.updateUser();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.isChange ? "已取消修改" : "取消确认"
          });
        });
    },
    async addUser() {
      if (!this.form.username || this.form.username == "") {
        this.$message({
          type: "error",
          message: "请输入姓名"
        });
        return;
      } else if (!this.form.password || this.form.password == "") {
        this.$message({
          type: "error",
          message: "请输入密码"
        });
        return;
      } else if (!this.form.phone || this.form.phone == "") {
        this.$message({
          type: "error",
          message: "请输入手机号"
        });
        return;
      }
      this.loading = true;
      let addUserParas = {};
      addUserParas.username = this.form.username;
      addUserParas.password = this.form.password;
      addUserParas.phone = this.form.phone;
      if (this.form.role == "3") {
        addUserParas.role = 3;
      } else if (this.form.role == "2") {
        addUserParas.role = 2;
      }
      const res = await addUserInfo(addUserParas);
      this.loading = false;
      if (res.resCode == 0) {
        this.dialogFormVisible = false;
        this.$message({
          type: "success",
          message: "添加成功"
        });
        this.initData();
      } else {
        this.$message({
          type: "error",
          message: "添加失败，请重新添加"
        });
      }
    }
  }
};
</script>

<style lang="less">
@import "../style/mixin";
.table_container {
  padding: 20px;
}

.add_user {
  padding: 20px;
  float: right;
}

.type_change {
  padding: 20px;
  float: left;
}
</style>
